/*
 * @Author: wurangkun
 * @Date: 2024-05-14 12:00:38
 * @LastEditTime: 2024-05-22 15:52:51
 * @LastEditors: wurangkun
 * @FilePath: \flutter_example\lib\widgets\AnimatedList.dart
 * @Description: 动态添加 动画列表自动滑动到底部
 */
import 'package:flutter/material.dart';
import 'package:flutter_example/widgets/JButton.dart';

class AnimatedListPage extends StatefulWidget {
  const AnimatedListPage({super.key});

  @override
  State<AnimatedListPage> createState() => _AnimatedListPageState();
}

class _AnimatedListPageState extends State<AnimatedListPage> {
  final GlobalKey<AnimatedListState> listKey = GlobalKey<AnimatedListState>();
  late List<String> list = [];
  final ScrollController listController = ScrollController();
  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 5; i++) {
      list.add("Item $i");
    }
  }

  void insertItem() {
    final int index = list.length;
    setState(() {
      list.insert(index, 'new Item');
      listKey.currentState!.insertItem(index);
    });
    scrollToBottom();
  }

  void scrollToBottom() {
    listController.animateTo(
      listController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }

  void removeItemDialog(int index) async {
    if (await showCancelDialog() == true) {
      print("删除当前行");
      setState(() {
        listKey.currentState!.removeItem(
          index,
          (context, animation) {
            // 删除过程执行的是反向动画，animation.value 会从1变为0
            var item = _buildItem(context, index, animation);
            print('删除 ${list[index]}');
            list.removeAt(index);
            // 删除动画是一个合成动画：渐隐 + 收缩列表项
            return FadeTransition(
              opacity: CurvedAnimation(
                parent: animation,
                //让透明度变化的更快一些
                curve: const Interval(0.5, 1.0),
              ),
              // 不断缩小列表项的高度
              child: SizeTransition(
                sizeFactor: animation,
                axisAlignment: 0.0,
                child: item,
              ),
            );
          },
          duration: const Duration(milliseconds: 400), // 动画时间为 200 ms
        );
      });
    }
  }

  Future<bool?> showCancelDialog({String title = '确定删除吗？'}) async {
    bool? a = await showDialog<bool?>(
        context: context,
        builder: (builder) {
          return Center(
            child: Container(
              width: 280,
              height: 150,
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color: Colors.white,
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // Row(
                  //   crossAxisAlignment: CrossAxisAlignment.center,
                  //   children: [
                  //   ],
                  // ),

                  Container(
                    alignment: Alignment.center,
                    child: Text(
                      title,
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        decoration: TextDecoration.none,
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: Colors.black,
                      ),
                    ),
                  ),
                  const SizedBox(height: 20),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Center(
                        child: AnimatedButton(
                          text: '取消',
                          style: const TextStyle(
                            decoration: TextDecoration.none,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                            shadows: [
                              Shadow(
                                color: Color(0x80FF9700),
                                blurRadius: 10.0,
                                offset: Offset(4, 8),
                              ),
                            ],
                          ),
                          onTap: () {
                            Navigator.pop(context, false);
                          },
                        ),
                      ),
                      Center(
                        child: AnimatedButton(
                          text: "确认",
                          style: const TextStyle(
                            decoration: TextDecoration.none,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                            shadows: [
                              Shadow(
                                color: Color(0x80FF9700),
                                blurRadius: 10.0,
                                offset: Offset(4, 8),
                              ),
                            ],
                          ),
                          onTap: () {
                            Navigator.pop(context, true);
                          },
                        ),
                      )
                    ],
                  )
                ],
              ),
            ),
          );
        });
    return a;
  }

  Widget _buildItem(
      BuildContext context, int index, Animation<double> animation) {
    return SlideTransition(
      position: animation.drive(CurveTween(curve: Curves.easeInOutQuart)).drive(
          Tween<Offset>(begin: const Offset(1, 0), end: const Offset(0, 0))),
      child: InkWell(
        onTap: () {},
        onLongPress: () => removeItemDialog(index),
        child: ListTile(
          leading: CircleAvatar(
            backgroundColor: Colors.blue,
            child: Text("$index"),
          ),
          title: Text("Item $index"),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("AnimatedList"),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: insertItem,
        child: const Center(
          child: Text("add"),
        ),
      ),
      body: AnimatedList(
        controller: listController,
        key: listKey,
        initialItemCount: list.length,
        itemBuilder: (context, index, animation) =>
            _buildItem(context, index, animation),
      ),
    );
  }
}
